<template>
  <div>
        <!--修改页-->
        <el-form v-if="displayType==='edit'" label-width="95px" class="infoInput" :rules="rules" :model="menuinfo" ref="editForm">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="菜单名称" prop="menuName">
                        <el-input v-model="menuinfo.menuName" size="medium"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示顺序" prop="orderNum">
                        <el-input-number size="medium" v-model="menuinfo.orderNum" controls-position="right" :min="1" :max="300"></el-input-number>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                    <el-col :span="24">
                        <el-form-item label="上级菜单">
                            <el-select ref="menuEditSelect" size="medium" style="width:100%" :disabled="ifroot" v-model="menuinfo.parentName" clearable placeholder="请选择菜单">
                                    <el-option style="display:none" label="请选择" value="0"></el-option>
                                    <el-tree style="display:'inline-block'" ref="tree" 
                                    :data="menuViewTree" :props="defaultProps" @node-click="updateParentMenu($event,'edit')"></el-tree>
                                </el-select>
                        </el-form-item>
                    </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="菜单图标">
                        <el-select v-model="menuinfo.icon" style="width:100%" size="medium" placeholder="请选择菜单图标" @visible-change="getIcons">
                            <el-option v-for="item in iconOptions" :key="item.label" :value="item.label">
                                <i :class="item.label"></i>
                                {{item.label}}
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <!--
                    <el-col :span="12">
                    <el-form-item prop="permission">
                        <span slot="label">
                            <span class="span-box">
                                <el-tooltip style="diaplay:inline" effect="dark" content="该菜单项对应权限唯一标识，以英文字母组成" placement="top">
                                    <i class="el-icon-question" />
                                </el-tooltip>
                                <span>权限标识</span>
                            </span>
                        </span>
                        <el-input v-model="menuinfo.permission"  size="medium"></el-input>
                    </el-form-item>
                </el-col>
                -->
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item prop="path">
                        <span slot="label">
                            <span class="span-box">
                                <el-tooltip style="diaplay:inline" effect="dark" content="组件在项目结构下的路径,sa-view下文件夹名开头.vue结尾(目前仅支持vue文件" placement="top">
                                    <i class="el-icon-question" />
                                </el-tooltip>
                                <span>组件路径</span>
                            </span>
                        </span>
                        <el-input v-model="menuinfo.path"  size="medium"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item prop="url">
                        <span slot="label">
                            <span class="span-box">
                                <el-tooltip style="diaplay:inline" effect="dark" content="后端的接口路由地址，以/开头" placement="top">
                                    <i class="el-icon-question" />
                                </el-tooltip>
                                <span>接口地址</span>
                            </span>
                        </span>
                        <el-input v-model="menuinfo.url"  size="medium"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="菜单类型" prop="type">
                        <el-select size="medium" v-model="menuinfo.type" placeholder="类型修改">
                            <el-option label="目录" value="Z"></el-option>
                            <el-option label="菜单" value="M"></el-option>
                            <el-option label="按钮" value="B"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="菜单状态">
                        <el-radio v-model="menuinfo.status" label="启用" value="启用">启用</el-radio>
                        <el-radio v-model="menuinfo.status" label="停用" value="停用">停用</el-radio>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="是否外链">
                        <el-radio v-model="menuinfo.isBlank" label="1">是</el-radio>
                        <el-radio v-model="menuinfo.isBlank" label="0">否</el-radio>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否显示">
                        <el-radio v-model="menuinfo.isShow" label="1">是</el-radio>
                        <el-radio v-model="menuinfo.isShow" label="0">否</el-radio>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <div class="inlineBtn">
                        <el-button size="medium" type="primary" @click="updateSubmit">提交</el-button>
                        <el-button size="medium" @click="noUpdate">关 闭</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>
        <!--新增页-->
        <el-form v-if="displayType==='add'" label-width="95px" class="infoInput" :rules="rules" :model="newmenu" ref="addForm">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="菜单名称" prop="menuName">
                        <el-input v-model="newmenu.menuName"  size="medium"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示顺序" prop="orderNum">
                        <el-input-number v-model="newmenu.orderNum" size="medium" controls-position="right" :min="1" :max="300"></el-input-number>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="上级菜单" prop="parentName">
                        <el-select ref="menuAddSelect"  size="medium" style="display: block;width:100%" :disabled="ifrow" v-model="newmenu.parentName" clearable placeholder="请选择菜单">
                                <el-option style="display:none" label="请选择" value="0"></el-option>
                                <el-tree style="display:'inline-block'" ref="tree" 
                                :data="menuViewTree" :props="defaultProps" @node-click="updateParentMenu($event,'add')"></el-tree>
                            </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                    <el-col :span="12">
                        <el-form-item label="菜单图标">
                            <el-select v-model="newmenu.icon"  size="medium" placeholder="请选择" @visible-change="getIcons">
                                <el-option v-for="item in iconOptions" :key="item.label" :value="item.label">
                                    <i :class="item.label"></i>
                                    {{item.label}}
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item prop="permission">
                            <span slot="label">
                                <span class="span-box">
                                    <el-tooltip style="diaplay:inline" effect="dark" content="该菜单项对应权限唯一标识，新增后将不可修改！请和开发人员做好沟通" placement="top">
                                        <i class="el-icon-question" />
                                    </el-tooltip>
                                    <span>权限标识</span>
                                </span>
                            </span>
                            <el-input v-model="newmenu.permission"  size="medium"></el-input>
                        </el-form-item>
                    </el-col>
            </el-row>
            <el-row>
                    <el-col :span="12">
                        <el-form-item prop="path">
                            <span slot="label">
                                <span class="span-box">
                                    <el-tooltip style="diaplay:inline" effect="dark" content="组件在项目结构下的路径,sa-view下文件夹名开头.vue结尾(目前仅支持vue文件" placement="top">
                                        <i class="el-icon-question" />
                                    </el-tooltip>
                                    <span>组件路径</span>
                                </span>
                            </span>
                            <el-input v-model="newmenu.path"  size="medium"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item prop="url">
                            <span slot="label">
                                <span class="span-box">
                                    <el-tooltip style="diaplay:inline" effect="dark" content="后端的接口路由地址，以/开头" placement="top">
                                        <i class="el-icon-question" />
                                    </el-tooltip>
                                    <span>接口地址</span>
                                </span>
                            </span>
                            <el-input v-model="newmenu.url"  size="medium"></el-input>
                        </el-form-item>
                    </el-col>
            </el-row>
            <el-row>
                    <el-col :span="12">
                        <el-form-item prop="type">
                            <span slot="label">
                                <span class="span-box">
                                    <el-tooltip style="diaplay:inline" effect="dark" content="该菜单项的类型，分别对应只在菜单栏展示/有实际页面/按钮" placement="top">
                                        <i class="el-icon-question" />
                                    </el-tooltip>
                                    <span>菜单类型</span>
                                </span>
                            </span>
                            <el-select v-model="newmenu.type"  size="medium" placeholder="类型修改">
                                <el-option label="目录" value="Z"></el-option>
                                <el-option label="菜单" value="M"></el-option>
                                <el-option label="按钮" value="B"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="菜单状态">
                            <el-radio-group v-model="newmenu.status">
                                <el-radio
                                    v-for="item in statusDictArr"
                                    :key="item.id" 
                                    :label="item.dictLabel" :value="item.dictValue">
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
            </el-row>
            <el-row>
                    <el-col :span="12">
                        <el-form-item>
                            <span slot="label">
                                <span class="span-box">
                                    <el-tooltip style="diaplay:inline" effect="dark" content="选择是外链则组件地址需要以`http(s)://`开头" placement="top">
                                        <i class="el-icon-question" />
                                    </el-tooltip>
                                    <span>是否外链</span>
                                </span>
                            </span>
                            <el-radio v-model="newmenu.isBlank" label="1">是</el-radio>
                            <el-radio v-model="newmenu.isBlank" label="0">否</el-radio>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否显示">
                            <el-radio v-model="newmenu.isShow" label="1">是</el-radio>
                            <el-radio v-model="newmenu.isShow" label="0">否</el-radio>
                        </el-form-item>
                    </el-col>
            </el-row>
            <el-row>
                    <el-col>
                        <div class="inlineBtn">
                            <el-button type="primary" size="medium" @click="addSubmit">提交</el-button>
                            <el-button size="medium" @click="noUpdate">关 闭</el-button>
                        </div>
                    </el-col>
            </el-row>
        </el-form>
  </div>
</template>

<script>
import icons from '../../sa-resources/icon.js'
export default {
    data(){
        //菜单名深度校验规则
        var validateMenuName = (rule, value, callback) => {
            //中文校验
            const cnReg=/[^u4e00-u9fa5]/; // eslint-disable-line
            if(!cnReg.test(value)){
                callback(new Error('菜单名必须由中文组成'));
            }else{
                callback();
            }
        };
        //组件路径深度校验规则
        var validatePath = (rule, value, callback) => {
            let menu;
            if(this.newmenu.menuName!==undefined){
                menu=this.newmenu
            }else{
                menu=this.menuinfo
            }
            //目录和按钮没有组件地址
            if(menu.type=="Z"||menu.type=="B"){
                callback()
            }else{
                if(menu.isBlank=='1'){
                    if(!this.sa.isUrl(value)){
                        callback("菜单为外链，组件地址应由http(s)://开头！")
                    }else{
                        callback()
                    }
                }else{
                    let path;
                    if(value==undefined){
                        callback("菜单不为外链,组件地址应由.vue结尾！")
                    }
                    path=value.slice(value.length-4)
                    //console.log(path);
                    if(path!=='.vue'){
                        callback("菜单不为外链,组件地址应由.vue结尾！")
                    }else{
                        callback()
                    }
                }
            }
            
        };
        //接口地址深度校验规则
        var validateUrl = (rule, value, callback) => {
            let menu;
            if(this.newmenu.menuName!==undefined){
                menu=this.newmenu
            }else{
                menu=this.menuinfo
            }
            if(menu.type=="Z"||menu.type=="M"){
                callback()
            }else{
                if(menu.isBlank=='1'){
                    callback()
                }else{
                    let url;
                    if(value==undefined){
                        callback("接口地址须以/开头！")
                    }
                    url=value.slice(0,1)
                    //console.log(path);
                    if(url!=='/'){
                        callback("接口地址须以/开头！")
                    }else{
                        callback()
                    }
                }
            }
            
        };
        //权限标识深度校验规则
        var validatePerm = (rule, value, callback) => {
            //英文字母校验
            const reg=/^[A-Za-z:]+$/ // eslint-disable-line
            if(!reg.test(value)){
                callback(new Error('权限标识必须由英文和冒号组成'));
            }else if(this.permissionList.includes(value)){
                callback(new Error('菜单权限标识与已存在权限标识重复'));
            }else{
                callback();
            }
        };
        return{
            defaultProps: {//组织树参数配置
              children: 'children',
              label: 'menuName'
            },
            iconOptions: [],//图标数组
            menuinfo:JSON.parse(this.menu),//当前菜单信息
            menuViewTree:[{id:'0',menuName:'全知视角',children:this.menuTree}],
            permissionList:[],
            newmenu:{
                parentName:'',
                orderNum:1,
                status:'启用',
                isShow:'1',
                isBlank:'0'
            },
            //表单校验规则
            rules:{
                menuName: [
                    { required: true, message: '请输入菜单名', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 2 到 6 个字符', trigger: 'blur' },
                    { validator: validateMenuName, trigger: 'blur'}
                ],
                orderNum: [
                    { required: true, message: '请设置菜单显示顺序', trigger: 'change' }
                ],
                parentName: [
                  { required: true, message: '请设置父级菜单', trigger: 'change' }
                ],
                path:[
                    { validator: validatePath, trigger: 'blur'}
                ],
                url:[
                    { validator: validateUrl, trigger: 'blur'}
                ],
                permission:[
                    { required: true, message: '请输入权限标识', trigger: 'blur' },
                    { min: 2, max: 22, message: '长度在 2 到 22 个字符', trigger: 'blur' },
                    { validator: validatePerm, trigger: 'blur'}
                ],
                type: [
                    { required: true, message: '请设置菜单类型', trigger: 'change' }
                ]
            },
            ifrow:false,//新增页的修改上级菜单是否禁用
            ifroot:false,//修改页的修改上级菜单是否禁用
            statusDictArr:[]//状态字典
        }
    },
    props:['displayType','addType','menu','menuTree','idList','nameList'],
    methods:{
        //修改父级菜单时触发
        updateParentMenu(params,type){
            console.log(params);//传递的就是点击的树节点数据
            if(type==="edit"){
                if(params.id=="0"){
                    this.menuinfo.parentId=params.id
                    this.menuinfo.parentName="全知视角"
                    this.$refs.menuEditSelect.blur();
                    return
                }
                if(this.menuinfo.id==params.id){
                    this.$message.warning("禁止套娃！")
                    return
                }
                let flag=this.idList.includes(params.id);
                if(flag==true){
                    let index=this.idList.lastIndexOf(params.id)
                    this.menuinfo.parentId=params.id
                    this.menuinfo.parentName=this.nameList[index]
                    this.$refs.menuEditSelect.blur();
                }else{
                    this.$notify({
                        title: '警告',
                        message: '目前最多只支持到三级组织，请重新选择！',
                        type: 'warning'
                    });
                }
            }
            if(type=="add"){
                if(params.id=="0"){
                    this.newmenu.parentId=params.id
                    this.newmenu.parentName="全知视角"
                    this.$refs.menuAddSelect.blur();
                    return
                }
                if(this.newmenu.id==params.id){
                    this.$message.warning("禁止套娃！")
                    return
                }
                let flag=this.idList.includes(params.id);
                if(flag==true){
                    let index=this.idList.lastIndexOf(params.id)
                    this.newmenu.parentId=params.id
                    this.newmenu.parentName=this.nameList[index]
                    this.$refs.menuAddSelect.blur();
                }else{
                    this.$notify({
                        title: '警告',
                        message: '目前最多只支持到三级组织，请重新选择！',
                        type: 'warning'
                    });
                }
            }
        },
        //获取icon数组
        getIcons(flag){
            //console.log(flag);
            //这个事件会在下拉框显示和隐藏的时候都触发,但是判断flag的话，如果再次点击options,重复请求就会推相同的数据进去，所以不能用flag判断
            if(this.iconOptions.length==0){
                for (let index = 0; index < icons.length; index++) {
                    const element = icons[index];
                    this.iconOptions.push({label:element})
                }
            }
        },
        //修改提交
        updateSubmit(){
            if(!this.checkForm('editForm')){
                return
            }
            let params=this.menuinfo;
            params=this.sa.displaceIntStatus(this.menuinfo);
            console.log(this.menuinfo);
            this.request('/api/menu/update',params).then(res=>{
              if(!res){return}
              this.$bus.$emit("updateMenuCallback",this.menuinfo)
            })
        },
        //新增提交
        addSubmit(){
            if(!this.checkForm('addForm')){
                return
            }
            console.log(this.newmenu);
            let params=this.sa.displaceIntStatus(this.newmenu);
            this.request('/api/menu/add',params).then(res=>{
              if(!res){return}
              this.$bus.$emit("addMenuCallback")
            })
        },
        //表单提交前置校验
        checkForm(formName){
            let flag;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    flag=true;
                    return true;
                } else {
                    flag=false
                    return false;
                }
            });
            return flag
        },
        //取消修改
        noUpdate(){
            this.$bus.$emit("noUpdate")
        }
    },
    mounted(){
        //console.log(this.menuinfo);
        //如果修改的一级菜单，则禁用选择上级菜单
        if(this.displayType==="edit"&&this.menuinfo.parentId=="0"){
            this.ifroot=true
        }
        //修改状态，获取对应的状态字典详情
        if(this.displayType==="edit"){
            console.log(this.menuinfo);
            this.menuinfo=this.sa.displaceStrStatus(this.menuinfo)
            this.statusDictArr=this.sa.getDictByid("1")
        }
        //新增状态，则获取状态字典
        if(this.displayType==="add"){
            this.statusDictArr=this.sa.getDictByid("1")
            //console.log(this.statusDictArr);
        }
        //如果是行新增，固定上级菜单
        if(this.displayType==="add"&&this.addType==="rowadd"){
            //console.log("go?");
            this.newmenu.parentName=this.menuinfo.menuName
            this.newmenu.parentId=this.menuinfo.id
            this.ifrow=true
        }
        //获取已存在的权限标识，做唯一校验
        this.request('/api/menu/getAllMenuPermission').then(res=>{
          if(!res){return}
          this.permissionList=res.data
          //如果是修改页，移除原本的权限标识，防止没改标识还会报重复（因为原标识已存在数据库中了
          if(this.displayType==="edit"){
            let index=this.permissionList.indexOf(this.menuinfo.permission);
            this.permissionList.splice(index,index+1);
            //console.log(this.permissionList);
          }
        })
        //console.log(this.ifrow);
        //console.log(this.menuViewTree);
    }
}
</script>

<style lang="scss">
/*表单input框样式控制 */
.infoInput >div>div>div>div>div>input{
  width:90%;
}
/*修改页按钮 */
.inlineBtn {
    text-align:center
}

</style>